package com.budwk.app.sqfwV2.service.dayingRoad;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.budwk.app.sqfw.constants.SqfwFormSummaryConstants;
import com.budwk.app.sqfw.constants.SqfwWebSocketMsgConstants;
import com.budwk.app.sqfw.enums.DownLoadFileNameEnum;
import com.budwk.app.sqfw.models.Sqfw_completeflow;
import com.budwk.app.sqfw.models.Sqfw_formSummary_new;
import com.budwk.app.sqfw.services.SqfwCompleteflowService;
import com.budwk.app.sqfw.services.SqfwFormsummaryNewService;
import com.budwk.app.sqfw.vo.GenerateExcelUrlVO;
import com.budwk.app.sqfw.vo.GenerateWordAndPdfUrlVO;
import com.budwk.app.sqfw.vo.SqfwCustomForAdminCommonVO;
import com.budwk.app.sqfwDoc.bo.ExcelCreateConfig;
import com.budwk.app.sqfwDoc.codeGenerator.impl.SqfwTemplatePdfCommonService;
import com.budwk.app.sqfwDoc.codeGenerator.pdfGenerate.AbstractCustomerPdfCreateField;
import com.budwk.app.sqfwDoc.codeGenerator.pdfGenerate.BaseTemplatePdfGenerator;
import com.budwk.app.sqfwDoc.codeGenerator.pdfGenerate.SqfwPdfCreateCommonBO;
import com.budwk.app.sqfwV2.dto.dayingRoad.DaYingLuRedRecordPdfDTO;
import com.budwk.app.sqfwV2.dto.dayingRoad.DaYingLuWhiteRecordPdfDTO;
import com.budwk.app.sqfwV2.enums.RedWhite;
import com.budwk.app.sqfwV2.enums.RedWhitePdf;
import com.budwk.app.sqfwV2.generator.dayingRoadPdf.*;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.util.StrUtil;
import com.budwk.app.util.adminUtils.CommonCheckUtils;
import com.budwk.app.util.poiUtils.CommonFormOfficeUtils;
import com.budwk.starter.common.page.Pagination;
import com.budwk.starter.security.utils.SecurityUtil;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.data.PictureRenderData;
import com.deepoove.poi.data.Pictures;
import com.deepoove.poi.xwpf.NiceXWPFDocument;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Criteria;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

import java.util.*;
import java.util.stream.Collectors;

import static com.budwk.app.util.poiUtils.CommonFormOfficeUtils.createConvergePdfAndUpload;
import static com.budwk.app.util.poiUtils.CommonFormOfficeUtils.generateWordDocument;

/**
 * 本代码由代码生成器生成，版本号1.0
 */
@IocBean
@Slf4j
public class DaYingLuRedWhiteRecordPdfService extends SqfwTemplatePdfCommonService {

    @Inject
    SysUserService sysUserService;
    @Inject
    SqfwFormsummaryNewService sqfwFormsummaryNewService;
    @Inject
    SqfwCompleteflowService sqfwCompleteflowService;

    /**
     * 获取数据
     * @return
     */
    public Pagination list(Integer pageNo, Integer pageSize, String query) {
        // 构造查询条件
        Criteria cri = Cnd.cri();
        SqlExpressionGroup criSql = cri.where();

        criSql.andEquals(Sqfw_formSummary_new::getType, getSummaryType());

        if (StringUtils.isNotBlank(query)) {
            criSql.andEquals("param_data->>'celebratoryEvents'", query);
        }

        // 设置五级
        CommonCheckUtils.checkAreaRange(criSql);

        cri.getOrderBy().desc(Sqfw_formSummary_new::getFillDate);

        log.info("DoorThreeCareForAdminServiceImpl-list-SQL: {}", cri);
        Pagination pagination = sqfwFormsummaryNewService.listPage(pageNo, pageSize, cri);

        return pagination;
    }

    public void generatePdf(Sqfw_formSummary_new formSummary) {
        Sys_user user = sysUserService.getUserById(SecurityUtil.getUserId());
        Cnd cnd = Cnd.NEW();
        cnd.and(Sqfw_completeflow::getFileType, "=", getSummaryType());
        cnd.and(Sqfw_completeflow::getUserId, "=", user.getId());
        Sqfw_completeflow sqfwCompleteflow = sqfwCompleteflowService.fetch(cnd);
        if (sqfwCompleteflow == null) {
            sqfwCompleteflow = new Sqfw_completeflow();
        }
    }

    /**
     * 红白事pdf合集下载
     * @param excelConfigList
     * @param sqfwIdList
     * @return
     */
    public List<GenerateExcelUrlVO> downPdfList(List<ExcelCreateConfig> excelConfigList, List<String> sqfwIdList,
                                                String startTime, String endTime) {

        List<GenerateExcelUrlVO> generateExcelUrlVOS = new ArrayList<>();

        for (ExcelCreateConfig config : excelConfigList) {

            // 模板下载
            if (config.getOnlyGenerateTemplateFlag()) {
                GenerateExcelUrlVO urlVO = new GenerateExcelUrlVO();
                String url = downWordTemplate(config);
                urlVO.setExcelUrl(url);
                generateExcelUrlVOS.add(urlVO);
                return generateExcelUrlVOS;
            }

            // 数据下载
            String fileName;
            String celebratoryEvents;
            if (RedWhitePdf.RED_TRACKING_REPORT.getCode().equals(config.getFileIdentity())) {
                fileName = RedWhitePdf.RED_TRACKING_REPORT.getName();
                celebratoryEvents = RedWhite.RED.getName();
            } else {
                fileName = RedWhitePdf.WHITE_INFORMATION_STATISTICS.getName();
                celebratoryEvents = RedWhite.WHITE.getName();
            }
            String sql = "select sc.resource_path from shequ.sqfw_completeflow sc left join shequ.sqfw_form_summary_new sfsn " +
                    "on sc.id = sfsn.sqfw_flow_id where " +
                    "sfsn.param_data->>'celebratoryEvents' = '"+ celebratoryEvents +"' and sc.sqfw_id in"+ StrUtil.formatIds(sqfwIdList) +
                    "and sc.resource_path != 'error' and sc.resource_path != 'creating' ";
                    if (StringUtils.isNotBlank(startTime)) {
                        sql += "and sfsn.fill_date >= '"+startTime+"' ";
                    }
                    if (StringUtils.isNotBlank(endTime)) {
                        sql += "and sfsn.fill_date <= '"+endTime+" 23:59:59' ";
                    }
            sql += "order by sc.create_date asc";
            List<Sqfw_completeflow> completeFlowList = sqfwCompleteflowService.listEntity(Sqls.create(sql));

            GenerateExcelUrlVO generateExcelUrlVO = new GenerateExcelUrlVO();
            generateExcelUrlVO.setFileIdentity(config.getFileIdentity());

            if (completeFlowList != null && completeFlowList.size() > 0) {
                generateExcelUrlVO.setCreateConditionFlag(true);
            } else {
                generateExcelUrlVO.setCreateConditionFlag(false);
            }

            // 数据检测
            if (!config.getCreateExcelFileFlag() || completeFlowList == null || completeFlowList.size() == 0) {
                generateExcelUrlVOS.add(generateExcelUrlVO);
                continue;
            }

            List<String> pdfList = completeFlowList.stream().map(Sqfw_completeflow::getResourcePath).collect(Collectors.toList());

            try {
                String url = createConvergePdfAndUpload(pdfList, fileName);
                generateExcelUrlVO.setExcelUrl(url);
            } catch (Exception e) {
                e.printStackTrace();
            }
            generateExcelUrlVOS.add(generateExcelUrlVO);
        }

        return generateExcelUrlVOS;
    }

    @Override
    public AbstractCustomerPdfCreateField getPdfCreateField(Sqfw_formSummary_new formSummary) {
        DaYingLuWhiteRecordPdfDTO pdfDTO = JSONUtil.toBean(formSummary.getParamData(), DaYingLuWhiteRecordPdfDTO.class);
        String celebratoryEvents = pdfDTO.getCelebratoryEvents();
        if (RedWhite.RED.getName().equals(celebratoryEvents)) {
            return JSONObject.parseObject(formSummary.getParamData(), DaYingLuRedRecordPdfDTO.class);
        } else {
            return JSONObject.parseObject(formSummary.getParamData(), DaYingLuWhiteRecordPdfDTO.class);
        }
    }

    /**
     * 第五张表中的需要的类型，详情见 {@link com.budwk.app.sqfw.constants.SqfwFormSummaryConstants}
     *
     * @return 返回数据
     */
    @Override
    public String getSummaryType() {
        return SqfwFormSummaryConstants.red_white_record;
    }

    /**
     * 当pdf生成成功的时候，sock发送什么样的消息至前端
     * 参照{@link com.budwk.app.sqfw.constants.SqfwWebSocketMsgConstants}
     *
     * @return 结果
     */
    @Override
    public String getPdfCreateSocketType() {
        return SqfwWebSocketMsgConstants.work_flow_pdf_created;
    }

    /**
     * 创建下载文件的名称
     * 可以参照 {@link com.budwk.app.sqfw.enums.DownLoadFileNameEnum}
     * 注意！！！ 不用加上.pdf或者.word后缀
     *
     * @param completeFlow   工作流
     * @param formSummaryNew 表单数据
     * @return 结果
     */
    @Override
    protected String getDownloadFileName(Sqfw_completeflow completeFlow, Sqfw_formSummary_new formSummaryNew) {
        DaYingLuWhiteRecordPdfDTO pdfDTO = JSONUtil.toBean(formSummaryNew.getParamData(), DaYingLuWhiteRecordPdfDTO.class);
        String celebratoryEvents = pdfDTO.getCelebratoryEvents();
        return RedWhite.RED.getName().equals(celebratoryEvents) ? "婚事办理酒席备案表" : "丧事办理酒席备案表";
    }

    @Override
    protected List<BaseTemplatePdfGenerator> getPdfGenerator(Sqfw_completeflow completeFlow, Sqfw_formSummary_new formSummary) {
        List<BaseTemplatePdfGenerator> generatorList = Lists.newArrayList();
        // 在这里添加自己的generator
        DaYingLuWhiteRecordPdfDTO pdfDTO = JSONUtil.toBean(formSummary.getParamData(), DaYingLuWhiteRecordPdfDTO.class);
        String celebratoryEvents = pdfDTO.getCelebratoryEvents();
        if (RedWhite.RED.getName().equals(celebratoryEvents)) {
            generatorList.add(new RedHandleCateringRecordsPdfGenerator());
            generatorList.add(new RedAndWhiteCivilizedAndThriftyGenerator());
            generatorList.add(new RedAndWhiteSecurityGenerator());
        } else {
            generatorList.add(new WhiteHandleCateringRecordsPdfGenerator());
            generatorList.add(new RedAndWhiteCivilizedAndThriftyGenerator());
            generatorList.add(new RedAndWhiteSecurityGenerator());
            generatorList.add(new RedAndWhiteDiscourageGenerator());
        }
        return generatorList;
    }

    @Override
    public void customerPopularPdfCreateParam(SqfwPdfCreateCommonBO pdfCreateCommonBO, Sqfw_completeflow completeFlow, Sqfw_formSummary_new formSummary) {
        Sys_user user = sysUserService.getUserById(formSummary.getCreateBy());
        HashMap<String, Object> map = new HashMap<>();
        map.put("signature", user.getSignatureUrl());
        pdfCreateCommonBO.setCustomerParamMap(map);
    }

    /**
     * 下载word模板
     * @param config
     * @return
     */
    private String downWordTemplate(ExcelCreateConfig config) {
        String fileName = "";

        Map<String, Object> dataMap = JSONUtil.parseObj(new Sqfw_formSummary_new(), false);
        List<NiceXWPFDocument> xwpfDocumentList = new ArrayList<>();

        if (RedWhitePdf.WHITE_INFORMATION_STATISTICS.getCode().equals(config.getFileIdentity())) {
            fileName = RedWhitePdf.WHITE_INFORMATION_STATISTICS.getName();
            dataMap.putAll(JSONUtil.parseObj(new DaYingLuWhiteRecordPdfDTO(), false));

            xwpfDocumentList.add(getNiceXWPFDocument(dataMap, new WhiteHandleCateringRecordsPdfGenerator().getTemplateName()));
            xwpfDocumentList.add(getNiceXWPFDocument(dataMap, new RedAndWhiteCivilizedAndThriftyGenerator().getTemplateName()));
            xwpfDocumentList.add(getNiceXWPFDocument(dataMap, new RedAndWhiteSecurityGenerator().getTemplateName()));
            xwpfDocumentList.add(getNiceXWPFDocument(dataMap, new RedAndWhiteDiscourageGenerator().getTemplateName()));
        }
        if (RedWhitePdf.RED_TRACKING_REPORT.getCode().equals(config.getFileIdentity())) {
            fileName = RedWhitePdf.RED_TRACKING_REPORT.getName();
            dataMap.putAll(JSONUtil.parseObj(new DaYingLuRedRecordPdfDTO(), false));

            xwpfDocumentList.add(getNiceXWPFDocument(dataMap, new RedHandleCateringRecordsPdfGenerator().getTemplateName()));
            xwpfDocumentList.add(getNiceXWPFDocument(dataMap, new RedAndWhiteCivilizedAndThriftyGenerator().getTemplateName()));
            xwpfDocumentList.add(getNiceXWPFDocument(dataMap, new RedAndWhiteSecurityGenerator().getTemplateName()));

        }

        GenerateWordAndPdfUrlVO vo = CommonFormOfficeUtils.wordUpload(xwpfDocumentList, fileName.replace("合集", "模板"));
        return vo.getWordUrl();
    }

    /**
     * 生成单个word
     * @param dataMap
     * @param templateName
     * @return
     */
    private NiceXWPFDocument getNiceXWPFDocument(Map<String, Object> dataMap, String templateName) {
        for (String key : dataMap.keySet()) {
            dataMap.put(key, "");
        }
        dataMap.put("yyyy", "");
        dataMap.put("mm", "");
        dataMap.put("dd", "");
        dataMap.put("hh", "");
        dataMap.put("checkedUnitLeaders", new ArrayList<>());
        dataMap.put("signatures", new ArrayList<>());
        dataMap.put("visitPictures", new ArrayList<>());
        dataMap.put("fillDateStr", "");
        dataMap.put("title", "XX");
        dataMap.put("boardOfGovernors", "");

        XWPFTemplate xwpfTemplate = generateWordDocument(dataMap, null, templateName);
        return xwpfTemplate.getXWPFDocument();
    }
}
